package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.UserOrderService;
import com.sky.vo.AddressBookVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class UserOrderServiceImpl implements UserOrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //0.简单校验
        //01 地址是否存在
        AddressBookVO addressBookVO = addressBookMapper.selectAddressById(ordersSubmitDTO.getAddressBookId());
        if(Objects.isNull(addressBookVO)){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //02.谁的购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        if (CollectionUtils.isEmpty(shoppingCarts)){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //1.修改订单状态
        Orders orders = new Orders();
        //订单号采用时间戳
        String number = String.valueOf(System.currentTimeMillis());
        orders.setNumber(number);
        //修改为待接单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddressBookId(ordersSubmitDTO.getAddressBookId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(ordersSubmitDTO.getPayMethod());
        orders.setPayStatus(Orders.UN_PAID);
        //todo 金额计算 购物车所有的数量(商品的数量*商品单价)
        BigDecimal amount = new BigDecimal(ordersSubmitDTO.getPackAmount()+6);
        for (int i = 0; i < shoppingCarts.size(); i++) {
            ShoppingCart item = shoppingCarts.get(i);
            Integer numberItem = item.getNumber();
            BigDecimal amountItem = item.getAmount();
            amount = amount.add(amountItem.multiply(new BigDecimal(numberItem)));
        }
        orders.setAmount(amount);

        orders.setRemark(ordersSubmitDTO.getRemark());
        //todo 去地址表查询
        orders.setUserName(addressBookVO.getConsignee());
        orders.setPhone(addressBookVO.getPhone());
        String address = addressBookVO.getProvinceName()+addressBookVO.getCityName()+addressBookVO.getDistrictName()+addressBookVO.getDetail();
        orders.setAddress(address);
        orders.setConsignee(addressBookVO.getConsignee());

        orders.setEstimatedDeliveryTime(ordersSubmitDTO.getEstimatedDeliveryTime());
        orders.setDeliveryStatus(ordersSubmitDTO.getDeliveryStatus());
        orders.setPackAmount(ordersSubmitDTO.getPackAmount());
        orders.setTablewareNumber(ordersSubmitDTO.getTablewareNumber());
        orders.setTablewareStatus(ordersSubmitDTO.getTablewareStatus());
        //主键返回
        orderMapper.insert(orders);

        //2. 往订单详情表中写数据
        List<OrderDetail> orderDetailList = shoppingCarts.stream().map(shoppingCart1 -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1, orderDetail);
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());

        orderDetailMapper.insertBatch(orderDetailList);
        //3.清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        //4. 数据的返回和封装
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(number);
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        return orderSubmitVO;

    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return {@link PageResult}
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //1.开启
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //2.原始查询
        List<Orders> orders = orderMapper.selectByStatus(ordersPageQueryDTO.getStatus());
        //3.数据转换
        PageInfo<Orders> pageInfo = PageInfo.of(orders);
        List<Orders> ordersList = pageInfo.getList();

        //4.数据封装并返回
        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageInfo.getTotal());
        ordersList.forEach(orders1 -> {
            List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders1.getId());
            orders1.setOrderDetailList(orderDetailList);
        });
        pageResult.setRecords(ordersList);

        return pageResult;
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return {@link Orders}
     */
    @Override
    public Orders orderDetail(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (Objects.isNull(orders)){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        orders.setOrderDetailList(orderDetailList);
        return orders;
    }

    /**
     * 取消订单
     *
     * @param id <--> orderId
     */
    @Override
    @Transactional
    public void cancel(Long id) {
        //todo 删除订单表
        //todo 1.查询订单是否存在
        Orders orders = orderMapper.selectById(id);
        if (Objects.isNull(orders)){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //todo 2.查询订单状态是否大于2,如果大于2无法取消,因为是已结单后面的状态
        if(orders.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //todo 3.订单状态若处于待接单状态,需要退款

        //todo 4.更改订单状态、取消原因、取消时间
        orders.setStatus(orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //将原来的订单详情信息添加到购物车中
        // todo 1.查询订单详情信息
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        // todo 2.将订单详情信息转换为购物车信息
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        // todo 3.将订单详情信息批量添加到购物车中,即往数据库中写购物车信息
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (Objects.isNull(orders)){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type",2);//1.表示来单提醒,2.表示客户催单
        map.put("orderId",id);
        map.put("content","订单号:"+orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 模拟支付完成接口
     *
     * @param number
     */
    @Override
    public void paySuccess(String number) {
        Orders orders = new Orders();
        orders.setNumber(number);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayStatus(1);
        orderMapper.updateByNumber(orders);

        //支付完成,通过webSocket通知前端
        //Orders order = orderMapper.selectByNumber(number);
        HashMap<String,Object> params = new HashMap<>();
        params.put("type",1);
        params.put("orderId",orders.getId());
        params.put("content","订单号"+number);
        webSocketServer.sendToAllClient(JSON.toJSONString(params));
    }
}
